package com.woniuxy.automotivemanagementsystem.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.automotivemanagementsystem.entity.Menu;
import com.woniuxy.automotivemanagementsystem.entity.Role;
import com.woniuxy.automotivemanagementsystem.mapper.MenuMapper;
import com.woniuxy.automotivemanagementsystem.mapper.RoleMapper;
import com.woniuxy.automotivemanagementsystem.service.MenuService;
import com.woniuxy.automotivemanagementsystem.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Override
    public List<Menu> queryMenuByUid(Integer uid) {
        List<Menu> menus = menuMapper.queryMenuByUid(uid);//获取用户对应的菜单
        List<Menu> parentMenus = menus.stream().filter(menu -> menu.getPid() == 0).distinct().toList();
        for (Menu parentMenu : parentMenus) {
            List<Menu> childrenMenus = menus.stream().filter(menu -> menu.getPid().equals(parentMenu.getMid())).distinct().toList();
            parentMenu.setChildren(childrenMenus);
        }
        return parentMenus;
    }

    @Override
    public List<Menu> queryAllofTree() {
        //获取所有菜单
        List<Menu> menus = menuMapper.selectList( null);
        return createTreeNode(menus);
    }
    /*
    * 根据角色id查询关联的菜单信息
    * */
    @Override
    public List<Menu> queryMenuByRid(Integer rid) {
        List<Menu> menus = menuMapper.queryMenuByRid(rid);
        return createTreeNode(menus);
    }
    /*
    * 删除菜单接口，先判断角色和菜单的关联关系，再判断有无子菜单，再删除菜单
    * */
    @Override
    @Transactional
    public Result removeMenuByMid(Integer mid) {
        List<Role> roles = roleMapper.selectRolesByMid(mid);
        if(!roles.isEmpty()){
            return Result.error("此菜单被角色关联，请先解除关联关系");
        }
        List<Menu> childrenMenus = menuMapper.selectChildrenMenusByMid(mid);
        if(!childrenMenus.isEmpty()){
            return Result.error("此菜单有子菜单，请先删除子菜单");
        }
        menuMapper.deleteById( mid);
        return Result.success(true);
    }

    //    构造树形数据的方法
    private List<Menu> createTreeNode(List<Menu> menus){
        //创建一级菜单节点集合
        List<Menu> parentMenus = menus.stream().filter(menu -> menu.getPid() == 0).distinct().toList();
        //遍历一级菜单
        for (Menu parentMenu : parentMenus) {
            //创建二级菜单节点集合
            List<Menu> childrenMenus = menus.stream().filter(menu -> menu.getPid().equals(parentMenu.getMid())).distinct().toList();
            //设置二级菜单
            parentMenu.setChildren(childrenMenus);
        }
        return parentMenus;
    }
}
